  <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xHTML1/DTD/xHTML1-transitional.dtd">
<HTML XMLns="http://www.w3.org/1999/xHTML" lang="gb2312">
<head>
<title>test_trim</title>
<meta name="keywords" content="JS,事件冒泡,cancelBubble,stopPropagation" charset=utf-8/>
<!--[if !IE]> -->
  <script src="http://cdn.bootcss.com/jquery/2.2.0/jquery.min.js"></script>
  <!-- <![endif]-->
  <!--[if IE]>
      <script src="http://cdn.bootcss.com/jquery/1.12.0/jquery.js"></script>
  <![endif]-->
<style>
*{
  margin:0;
  padding:0;
}
</style>
</head>
<body>
<div>
  <input/>
  <button onclick="trimLeft()">提交</button>
</div>
<div id="result"></div> 
<script>
//供使用者调用  
function trim(s){  
    return trimRight(trimLeft(s));  
} 

//去掉左边的空白  
function trimLeft(){ 
var s ="    ahgnnd";
console.log(s); 
    if(s == null) {  
        return "";  
    }  
    var whitespace = new String(" \t\n\r"); //返回一个空格，一个tab，一个回车，一个回车符的对象
    console.log(whitespace);
    var str = new String(s);
    console.log(str);  
    if (whitespace.indexOf(str.charAt(0)) != -1) {  
        var j=0, i = str.length;  
        while (j < i && whitespace.indexOf(str.charAt(j)) != -1){  
            j++;  
        }  
        str = str.substring(j, i);  
    }
    console.log(str);  
    return str; 

}  

//去掉右边的空白  
function trimRight(s){  
    if(s == null) return "";  
    var whitespace = new String(" \t\n\r");  
    var str = new String(s);  
    if (whitespace.indexOf(str.charAt(str.length-1)) != -1){  
        var i = str.length - 1;  
        while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){  
           i--;  
        }  
        str = str.substring(0, i+1);  
    }  
    return str;  
}

</script>
</body>
</HTML>